<template>
  <div class="content-wrap content-container" v-loading="loading">
    <!-- 搜索区域 -->
    <el-form class="search-wrap" v-model="searchFormData">
      <el-form-item class="search-wrap-item" label="标题关键字：" prop="projectTitle">
        <el-input width="160px" placeholder="请输入标题关键字" v-model="searchFormData.projectTitle" clearable
          @input="getAllRequirements"></el-input>
      </el-form-item>
      <el-form-item class="search-wrap-item" label="时间：" prop="time">
        <el-date-picker style="width: 240px" type="daterange" unlink-panels range-separator="-" start-placeholder="开始时间"
          end-placeholder="结束时间" :value-on-clear="null" v-model="searchFormData.time" @change="getAllRequirements" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="createRequirementClick">创建需求</el-button>
      </el-form-item>
    </el-form>

    <!-- [我创建的需求]列表区域 -->
    <div class="card-layout-box" id="cardLayoutBox">
      <div class="card-not-requirement" v-if="allRequirements.length === 0">暂无数据</div>
      <!-- 未生效 -->
      <div class="card-box" v-if="allEnterReuirements.length !== 0">
        <!-- 分类 -->
        <div class="card-header-box" :style="{ backgroundColor: enterStatus(1)?.bgColor }">
          未生效：{{ allEnterReuirements.length }}
        </div>
        <!-- 需求列表 -->
        <div class="card-list-box">
          <ul class="card-list">
            <li class="card-list-item" v-for="item in allEnterReuirements" :key="item.ID">
              <div class="card-list-left">
                <!-- 需求标题 -->
                <div class="card-header-title-box" @click="handleRowClick(item.ID)">
                  <el-text class="w-150px mb-2" truncated tag="b">
                    {{ item.requirementName }}
                  </el-text>
                </div>
                 <!-- 任务附加信息 -->
                <div class="card-list">
                  <!-- 审核人：requirementAuditName -->
                  <div class="item-status" v-if="item.requirementAuditName">
                    <span>审核人：{{ item.requirementAuditName }}&nbsp;&nbsp;</span>
                    <span  :style="{ color: enterStatus(item.itemRequirementIsEnter).bgColor }">{{ enterStatus(item.itemRequirementIsEnter).text }}</span>
                  </div>

                  <!-- 技术负责人：itemRequirementIsEnter -->
                  <div class="card-list-small-item boss-name" v-if="item.itemRequirementIsEnter === 3">
                    <span style="color: #F56C6C;">请选择技术负责人：</span>
                    <el-dropdown :hide-on-click="false" placement="bottom" @command="handleReviewCommand">
                      <span class="el-dropdown-link">
                        <el-icon class="el-icon--right" color="#409EFF"><arrow-down /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item v-for="(review, index) in reviewNameOptions" :key="index" :command="{itemRequirementId: item.ID, nickName: review.nickName, uuid: review.uuid }">{{ review.nickName }}</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                  <div class="card-list-small-item begin-time">创建日期：{{ tableTimeDate(item.beginTime) }}</div>
                </div>
              </div>
              <!-- 操作 -->
              <div class="operate-box">
                <el-dropdown :hide-on-click="false" placement="bottom" @command="handleCommand">
                  <!-- 下拉图标 -->
                  <span class="el-dropdown-link">
                    <el-icon class="el-icon--right" color="#409EFF"><arrow-down /></el-icon>
                  </span>
                  <!-- 操作：itemRequirementIsEnter：1-待审核/催他/关闭；2-未通过/修改/审核记录/关闭；3-已通过/审核记录/关闭 -->
                  <template #dropdown>
                    <el-dropdown-menu>
                      <!-- 催他 -->
                      <el-dropdown-item v-if="item.itemRequirementIsEnter == 1" :command="{ type: 1, command: '催他', id: item.ID }">催他</el-dropdown-item>
                      <!-- <el-dropdown-item v-if="item.itemRequirementIsEnter == 2 || item.itemRequirementIsEnter == 3 || item.requirementAuditName == ''" :command="{ type: 2, command: '查看原因', id: item.ID }">查看原因</el-dropdown-item> -->
                      <!-- 修改 -->
                      <el-dropdown-item v-if="item.itemRequirementIsEnter == 2" :command="{ type: 2, command: '修改', id: item.ID }">修改</el-dropdown-item>
                      <!-- 审核记录 -->
                      <el-dropdown-item v-if="item.requirementAuditName !== '' && item.itemRequirementIsEnter !== 1" :command="{ type: 3, command: '审核记录', id: item.ID }">审核记录</el-dropdown-item>
                      <!-- 未分配技术负责人 -->
                      <el-dropdown-item v-if="item.requirementAuditName !== ''" :command="{ type: 0, command: '关闭', id: item.ID }">关闭</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </li>
          </ul>
        </div>
      </div>

      <!-- 已审核-分类 -->
      <div v-if="allFatherRequirements.length !== 0" class="card-box" v-for="(list, index) in fatherRequirements"
        :key="index">
        <div class="card-header-box" :style="{ backgroundColor: fatherStatus(list.status)?.bgColor }">
          {{ fatherStatus(list.status).text }}:{{ list.total }}
        </div>
        <!-- 需求列表 -->
        <div class="card-list-box">
          <ul class="card-list">
            <li class="card-list-item" v-for="item in list.requirements" :key="item.ID">
              <div class="card-list-left">
                <!-- 需求标题 -->
                <div class="card-header-title-box">
                  <el-text class="w-150px mb-2" truncated tag="b" @click="handleRowClick(item.ID)">
                    {{ item.requirementName }}
                  </el-text>
                </div>
                <!-- 附加信息 -->
                  <!-- 任务附加信息 -->
                  <div class="card-list">
                    <div class="card-list-small-item boss-name" v-if="item.requirementAuditName">审核人：{{ item.requirementAuditName }}</div>
                    <div class="card-list-small-item boss-name" v-if="item.requirementBossName">技术负责人：{{ item.requirementBossName == "" ? "无" :
                      item.requirementBossName }}</div>
                    <div class="card-list-small-item boss-name test-list" v-if="item.requirementRelevances">参与人：{{ item.requirementRelevances }}</div>
                    <div class="card-list-small-item begin-time">创建日期：{{ tableTimeDate(item.beginTime) }}</div>
                  </div>
              </div>
                <!-- 操作 -->
                <div class="operate-box" v-if="item.requirementFatherStatus !== 9">
                  <el-dropdown :hide-on-click="false" placement="bottom" @command="handleCommand">
                    <span class="el-dropdown-link">
                      <el-icon class="el-icon--right" color="#409EFF"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{ type: 0, command: '关闭', id: item.ID }">关闭</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 需求详情弹窗 -->
    <el-dialog v-if="dialogInfoVisible" style="width: 1200px;" :close-on-click-modal="false" v-model="dialogInfoVisible" @close="handleCloseDiglog" @closed="handleCloseDiglog">
        <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData"></CommonRequirementInfoVue>
    </el-dialog>

    <!-- 查看审核记录弹窗 -->
    <el-dialog style="width: 600px;" title="审核记录" :close-on-click-modal="false" v-model="dialogRecordVisible" @close="handleCloseDiglog">
      <el-timeline style="max-width: 560px; max-height: 500px; padding: 20px; overflow-y: auto;">
        <el-timeline-item
          v-for="(record, index) in recordData"
          :key="index"
          :timestamp="`审核时间：${tableTimeDateMsg(record.reviewDate)}`"
          :color="record.isEnter == 1 ? '#F56C6C' : record.isEnter == 2 ? '#E6A23C' :  record.isEnter == 3 ? '#67C23A' : '#F56C6C'"
          placement="top"
        >
        <el-card>
          <div class="record-title">
            <p>
              <span style="font-weight: bold;">审核人：</span>
              <span>{{ record.reViewUserName }}</span>
            </p>
            <p>
              <span style="font-weight: bold;">审核结果：</span>
              <span :style="{ color: enterStatus(record.isEnter).bgColor}">{{ enterStatus(record.isEnter).content }}</span>
            </p>
            <p>
              <span style="font-weight: bold;">评分：</span>
              <span>{{ record.reViewContentNumber }}</span>
            </p>
          </div>
          <!-- 评语 -->
          <div>
            <span style="font-weight: bold;">&nbsp;&nbsp;评语：</span>
            {{ record.reViewContent }} 
          </div>
          <!-- 需求草稿文档下载 -->
          <div class="info-file-box" v-if="record.worldUrl !== ''">
              <p class="info-content-title"><span style="font-weight: bold;">需求草稿：</span></p>
              <ul class="info-file-ul">
                  <li class="info-file-item" v-for="(item, index) in handleRecordFiles(record.worldUrl)" :key="index" @click="handleDownloadFile(item, baseUrl)">
                    <el-icon :size="12"><Document /></el-icon>
                    <span style="font-size: 12px;">&nbsp;{{ item.name }}</span>
                  </li>
              </ul>
          </div>
        </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <!-- 修改需求弹窗 -->
     <el-dialog class="again-dialog" style="width: 1200px;max-height: 700px;overflow-y: auto;" :close-on-click-modal="false" v-model="dialogAgainVisible" title="修改需求" @close="handleColseAgain" @closed="handleColseAgain" @before-close="handleColseAgain">
      <el-form 
        class="create-form" 
        ref="ruleAgainFormRef"
        :rules="againRules"
        :model="againRequirementForm">
        <!-- 项目名称 -->
        <el-form-item
          label="项目名称："
          required
          style="width: 50%"
          prop="projectId"
        >
          <el-select
            v-model="againRequirementForm.projectId"
            filterable="true"
            placeholder="项目名称"
            fit-input-width
            clearable
            style="width: 200px"
            disabled
          >
            <el-option
              v-for="item in allProjectLists"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            />
          </el-select>
          <!-- <el-icon
            class="add-icon"
            :size="24"
            @click="dialogAddProVisible = true"
            ><CirclePlus
          /></el-icon> -->
        </el-form-item>
        <!-- 需求类型 -->
        <el-form-item
          label="需求类型："
          required
          style="width: 50%;"
          prop="projectType"
        >
          <el-radio-group v-model="againRequirementForm.projectType">
            <el-radio-button
              v-for="item in allTypeLists"
              :key="item.id"
              :label="item.type"
              :value="item.id"
            />
          </el-radio-group>
        </el-form-item>
        <!-- 需求标题 -->
        <el-form-item
          label="需求标题："
          required
          style="width: 50%"
          prop="projectTitle"
        >
          <el-input
            v-model="againRequirementForm.projectTitle"
            placeholder="请输入需求标题"
            style="width: 400px"
          ></el-input>
        </el-form-item>

        <!-- 预计上线时间 -->
        <el-form-item label="预计上线时间：" prop="onlineTime" style="width: 50%" required>
          <el-date-picker
            style="width: 180px"
            v-model="againRequirementForm.onlineTime"
            type="date"
            placeholder="请选择预计上线日期"
            :disabledDate="disabledDate"
          />
        </el-form-item>
        <!-- 需求详情 -->
        <el-form-item
          label="简述需求："
          required
          style="width: 100%; margin-bottom: 20px;"
          prop="projectMsg"
        >
          <div style="width: 100%;">
            <EditorVue
            v-if="dialogAgainVisible"
            style="width: calc(100% - 20px);"
            class="editor"
            :modelValue="againRequirementForm.projectMsg"
            @update:modelValue="updateModelValue"
          />
          </div>
        </el-form-item>

        <!-- 附件 -->
        <el-form-item
          label="&nbsp;&nbsp;附件："
          class="file-box"
          >
          <div v-if="(againRequirementForm.filePaths.length + fileList.length) == 0">无</div>
          <el-tag 
            style="cursor: pointer;margin-right: 5px;" 
            v-model="againRequirementForm.filePaths"
            v-for="(tag, index) in againRequirementForm.filePaths" :key="index" 
            closable="true" 
            type="primary" 
            @close="handleDelFile(tag.url)"
            @click="handleDownloadFile(tag, baseUrl)">
            {{ tag.name }}
        </el-tag>
        </el-form-item>
      
      <!-- 追加附件 -->
        <el-form-item
          class="upload-box"
          label="&nbsp;&nbsp;追加附件:"
        >
          <div style="width: 100%;">
            <el-upload 
              class="upload-demo"
              v-model:file-list="fileList"
              action=""
              multiple="true"
              :limit="(3 - againRequirementForm.filePaths.length)"
              :http-request="handleUpLoad"
              :on-success = "handleSuccess"
              :on-error="handleError"
              :on-remove = "handleRemove"
              :on-exceed = "handleExceed"
              >
              <el-button class="upload-btn" type="Default" size="small">+</el-button>
            </el-upload>
          </div>
        </el-form-item>

        <!-- 创建需求 -->
        <el-form-item class="create-button">
          <el-button type="primary" @click="handleColseAgain">取消</el-button>
          <el-button type="primary" id="againBtn" @click="handleAgainRequirement(ruleAgainFormRef)">修改</el-button>
        </el-form-item>
      </el-form>
     </el-dialog>

     <!-- 添加项目名称对话框 -->
    <!-- <el-dialog
      id="dialogForm"
      style="width: 400px; margin-top: 200px"
      v-model="dialogAddProVisible"
      title="添加项目"
       :close-on-click-modal="false"
      :show-close="true"
      :before-close="handleBeforeCancel"
    >
      <el-input
        placeholder="请输入项目名称"
        v-model="newProjectName"
      ></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleAddProjectDialog">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { ref, onMounted, reactive, } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElNotification, FormInstance  } from "element-plus";
import { ElForm } from "element-plus";
import {
  putCloseRequirementStatus, GetCreateRequirement, PutUpdateBossName, postAddItmeItem,
  GetUrgedRequriement, GetRequirementEnterMsg, PostRequirement, PostAgainRequirement,
} from "@/api/newDemands/index";
import { postUploadFile } from "@/api/common/index";
import { tableTimeDate, enterStatus, fatherStatus, tableTimeDateMsg, handleFileName, handleDownloadFile, isValidateEditor  } from "@/utils/utils";
import useCommonDataStore from "@/store/common/common";
import CommonRequirementInfoVue from "../comomRequirementInfo.vue";
import EditorVue from "@/views/experiment/demands/editor.vue";

let router = useRouter();
let useCommonStore = useCommonDataStore();
const loading = ref(false);
const userAuthId = ref<any>(null);//当前用户权限id
const allRequirements = ref<any>([]); // 我创建的所有已审核需求
const allFatherRequirements = ref([]);//定义我创建的所有已审核需求
const fatherRequirements = ref<any>([]);//定义我创建的所有已审核需求分类统计数据
const allEnterReuirements = ref<any>([]);// 定义我创建的所有待审核需求
const draftFiles = ref<any>([]);//该需求所有的需求草稿地址
const baseUrl = ref(import.meta.env.VITE_SERVE);//服务器地址
const searchFormData = ref({
  projectTitle: "",
  time: [null, null]
});//搜索关键字


const dialogAvgVisible = ref(false); //控制是否开启分配任务弹窗
const dialogInfoVisible = ref(false);//查看需求弹窗控件
const clearData = ref(false);//控制是否清空子组件数据
const dialogRecordVisible = ref(false);//控制查看审核记录弹窗控件
const dialogAgainVisible = ref(false);//控制审核未通过修改需求弹窗

const isRequirementID = ref(); //当前操作任务ID
const reviewNameOptions = ref<any>([]);//所有技术负责人选项列表
const recordData = ref<any>([]);//所有审核记录

/* 修改需求 */
const allProjectLists = ref<any>([]); // 定义所有项目名称列表
const allTypeLists = ref<any>([]); // 定义所有项目名称列表
const ruleAgainFormRef = ref<FormInstance>();// 表单实例
const fileList = ref<any>([]);//已上传的附件
const filePaths = ref([]);//所有上传文件响应地址
// const dialogAddProVisible = ref(false);//控制添加项目名称的弹窗
// const newProjectName = ref(""); // 临时存储新项目名称

// 修改需求表单数据
const againRequirementForm = reactive<any>({
  itemRequirementId: null,
  projectId: null,
  projectType: null,
  projectTitle: "",
  onlineTime: null,
  projectMsg: "",
  filePaths: []
});
// 表单验证规则
const againRules = reactive({
    projectId: [{ required: true, message: "请选择项目名称", trigger: "blur" }],
    projectType: [{ required: true, message: "请选择需求类型", trigger: "blur" }],
    projectTitle: [{ required: true, message: "请输入需求名称", trigger: "blur" }],
    onlineTime: [{ required: true, message: "请选择预计上线时间", trigger: "blur" }],
    projectMsg: [{ 
      required: true, 
      message: "请输入需求详情", 
      trigger: "blur", 
      validator: (rule: any, value: any, callback: any) => {
        // 调用自定义验证函数
        if (isValidateEditor(value)) {
          callback(new Error("需求详情不能为空格或空行！"));
        } else {
          callback();
        }
      }
    }], 
});



// 获取公共数据
const getCommon = async (index: any) => {
  await useCommonStore.getAllReqTypesList();
  await useCommonStore.getAllProjectList();
  await useCommonStore.getAllRoleUsersList(index);

  allProjectLists.value = useCommonStore.$state.allProjectList;
  allTypeLists.value = useCommonStore.$state.allReqTypesList;
};

// TODO 点击创建任务
const createRequirementClick = () => {
  router.push({
    path: "/requirement/create",
  });
};

// TODO 获取技术负责人下拉列表
const getReviewNameOptions = async () => {
  await useCommonStore.getAllRoleUsersList("555|999");
  reviewNameOptions.value = useCommonStore.$state.allRoleUserList;
};


// TODO 获取我创建的需求数据
const getAllRequirements = async () => {
  loading.value = true;
  userAuthId.value = localStorage.getItem("authorityId");

  const { data } = await GetCreateRequirement({
    projectTitle: searchFormData.value.projectTitle,
    beginTime: searchFormData.value.time === null ? null : searchFormData.value.time[0],
    endTime: searchFormData.value.time === null ? null : searchFormData.value.time[1]
  });

  if (data.code === 200) {
    if (data.data.requirements === null) {
      allRequirements.value = [];
      allEnterReuirements.value = [];
      allFatherRequirements.value = [];
      loading.value = false;
      return;
    } else {
      allRequirements.value = data.data.requirements;

      // 未生效且未关闭
      allEnterReuirements.value = data.data.requirements.filter((item: any) => item.itemRequirementIsEnter < 3).filter((item: any) => item.requirementFatherStatus !== 9);
      allEnterReuirements.value = data.data.requirements.filter((item: any) => item.requirementFatherStatus !== 8).filter((item: any) => item.requirementBossName == "");
      
      // 已审核或已关闭
      allFatherRequirements.value = data.data.requirements.filter((item: any) => 
      !allEnterReuirements.value.some((enterItem: any) => enterItem.ID === item.ID)
    );
    // allFatherRequirements.value = data.data.requirements.filter((item: any) => item.itemRequirementIsEnter === 3 || item.requirementFatherStatus === 8).filter((item:any) => item.requirementBossName !== "");
    
    console.log("已审核", allEnterReuirements.value);

      if (allFatherRequirements.value.length > 0) {
        // 1、将响应数据根据requirementFatherStatus进行分类并统计
        const statusCount = {} as any;

        allFatherRequirements.value.forEach((item: any) => {
          let fatherStatus = item.requirementFatherStatus;

          if (statusCount[fatherStatus]) {
            statusCount[fatherStatus].total++;
            // 判断该item是否已经添加
            if (!statusCount[fatherStatus].requirements.includes(item.ID)) {
              statusCount[fatherStatus].requirements.push(item);
            }
          } else {
            statusCount[fatherStatus] = {
              status: Number(fatherStatus),
              total: 1,
              requirements: [item]
            }
          }
        });

        fatherRequirements.value = Object.values(statusCount);
      }
      console.log(fatherRequirements.value);
      console.log(allEnterReuirements.value)
    }

    // 动态添加样式
    const cardLayoutBox = document.getElementById("cardLayoutBox");
    let enterLength = allEnterReuirements.value.length == 0 ? 0 : 1;
    let fatherLength = allFatherRequirements.value.length;

    if ((enterLength + fatherLength) % 3 == 2) {
      cardLayoutBox?.style.setProperty("justify-content", "flex-start");
    } else {
      cardLayoutBox?.style.setProperty("justify-content", "space-between");
    };
    console.log(enterLength+fatherLength,(enterLength+fatherLength) % 3);
    console.log(cardLayoutBox?.style.justifyContent);
  } else {
    ElMessage.error(data.msg);
    return;
  };
  loading.value = false;

};

// TODO 查看需求审核记录
const handleEnterMsg = async (id: number) => {
  dialogRecordVisible.value = true;

  const { data } = await GetRequirementEnterMsg(id);

  if(data.code === 200) {
    // 审核记录
    recordData.value = data.data;
  } else {
    ElMessage.error(data.msg);
    return;
  }
};

// TODO 处理每次审核的需求草稿
const handleRecordFiles = (val: string) => {
  // 需求草稿地址
  if(val !== "") {
      draftFiles.value = val.split("|").map((url: string) => {
        return handleFileName(url);
      });
  }
  return draftFiles.value;
};

// TODO 关闭主需求
const closeFatherStatus = async (id: number) => {
  await ElMessageBox.confirm("确认关闭该需求吗？", {
    confirmButtonText: "确认"
  }).catch(() => {
    return new Promise(() => { });
  });

  const { data } = await putCloseRequirementStatus({
    requirementId: id
  });
  if (data.code !== 200) {
    ElMessage.warning(data.msg);
    return;
  } else {
    await getAllRequirements();
  }
};


// TODO 查看需求
const handleRowClick = async (id: number) => {
  dialogInfoVisible.value = true;
  isRequirementID.value = id;
};

const handleInitAgain = () => {
  againRequirementForm.itemRequirementId = null;
  againRequirementForm.projectId = null;
  againRequirementForm.projectType = null;
  againRequirementForm.projectTitle =  "";
  againRequirementForm.onlineTime = null;
  againRequirementForm.projectMsg = "";
  againRequirementForm.filePaths = [];
};


// TODO 未生效操作
const handleCommand = async (val: any) => {

  switch (val.type) {
    case 0: 
      // 关闭需求
      await closeFatherStatus(val.id);
      break;
    case 1:
      await handleUrged(val.id);
      break;
    case 2:
      // 查询需求，获取需求原始数据
      try {
        const { data } = await PostRequirement({
            id: val.id,
        });
  
        if (data.code === 200) {
          console.log("当前需求：", data.data);
          
          // 需求草稿地址
          if (data.data.itemRequirementWorldDraft !== "" || data.data.itemRequirementWorldDraft.includes("|")) {
            if (data.data.itemRequirementWorldDraft.includes("|")) {
              againRequirementForm.filePaths = data.data.itemRequirementWorldDraft.split("|").map((url: string) => {
                  return handleFileName(url);
                });
            } else {
              againRequirementForm.filePaths[0] = handleFileName(data.data.itemRequirementWorldDraft);
            }
          } else {
            againRequirementForm.filePaths = [];
          };
          
          againRequirementForm.itemRequirementId = val.id;
          againRequirementForm.projectId = data.data.ItemItemId;
          againRequirementForm.projectType = data.data.itemRequirementTypeId;
          againRequirementForm.projectTitle =  data.data.requirementName.substring((data.data.requirementName.lastIndexOf('】') + 1));
          againRequirementForm.onlineTime = data.data.onlineTime;
          againRequirementForm.projectMsg = data.data.requirementContent;
          
          dialogAgainVisible.value = true;
          console.log("表单初始数据：", againRequirementForm);
          
        } else {
          ElMessage.error(data.msg);
          throw console.error(data.msg);
        };
      } catch (error) {
        console.log("获取数据失败：", error);
      }
      break;
    case 3:
      // 查看审核记录
      await handleEnterMsg(val.id);
      break;
    default: 
      // 关闭需求
      await closeFatherStatus(val.id);
      break;
  };
};

//  选择技术负责人
const handleReviewCommand = async (val: any) => {
  console.log("选择技术负责人：", val);

  await ElMessageBox.confirm(`确认技术负责人为：${val.nickName}吗？`, {
    confirmButtonText: "确认",
  }).catch(() => {
    console.log("取消选择技术负责人！");
    return new Promise(() => {});
  });

  const { data } = await PutUpdateBossName(val);
  if(data.code === 200) {
    ElMessage.success(data.msg);
    await getAllRequirements();
  } else {
    ElNotification({
      title: '',
      message: data.msg,
      type: 'warning',
      duration: 3000
    });
    return;
  }
}

// 催促审核需求
const handleUrged = async (id: number) => {
  const { data } = await GetUrgedRequriement(id);
  if (data.code === 200) {
    ElMessage.success("已催促");
  } else {
    ElMessage.error(data.msg);
  }
};


// TODO 关闭弹窗
const handleCloseDiglog = () => {
  // isRequirementID.value = null;
  clearData.value = true;
  dialogAvgVisible.value = false;

  dialogRecordVisible.value = false;
  recordData.value = [];
};

// TODO 规定预计上线时间为today及之后，之前的不可选
const disabledDate = (time: any) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

// ! 自定义上传文件
const handleUpLoad = (options: any) => {
  console.log("Options:", options);
  postUploadFile(options.file, "draftPath", "1").then(res => {
    options.onSuccess(res);
  }).catch(error => {
    options.onError(error);
  })
};


const handleSuccess = (v: any) => {
  if (v.data.data && v.data.data.resultFilePath) {
    // @ts-ignore
    filePaths.value.push(v.data.data);
  }
};

const handleError = (err: any) => {
  ElMessage.error(err);
};

const handleRemove = (v: any) => {
  fileList.value = fileList.value.filter((item: any) => item.name !== v.name);
  filePaths.value = filePaths.value.filter((path: any) => path.fileName !== v.name);
};

const handleExceed = (exc: any) => {
  ElMessage.warning("最多有3个附件！")
};

// TODO 删除附件
const handleDelFile = (val: any) => {
  const index = againRequirementForm.filePaths.findIndex((item: any) => item.url === val);
  if (index !== -1) {
    againRequirementForm.filePaths.splice(index, 1);
  }
};

// TODO 添加项目功能
/* const handleAddProjectDialog = async () => {
  loading.value = true;

  // 验证newProjectName是否为空
  if (newProjectName.value.trim() === "") {
    alert("请输入项目名称");
    return;
  } else if (
    allProjectLists.value.some(
      (item: any) => item.projectName === newProjectName.value
    )
  ) {
    alert("该项目已创建，请直接选择！");
    return;
  } else {
    // 发起添加项目请求
    const { data } = await postAddItmeItem({
      itemName: newProjectName.value,
    });
    if (data.code === 200) {
      dialogAddProVisible.value = false;
      ElMessage.success(data.msg);
      await getCommon(333);
      againRequirementForm.projectId = allProjectLists.value[allProjectLists.value.length-1].id;
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      dialogAddProVisible.value = false;
      loading.value = false;
      throw console.error(data.msg);
    }
  }
}; */

// 取消/关闭添加项目/需求类型功能
/* const handleCancel = () => {
  dialogAddProVisible.value = false;
  newProjectName.value = "";
};
const handleBeforeCancel = (done: any) => {
  dialogAddProVisible.value = false;
  newProjectName.value = "";
  done();
}; */


// TODO 取消修改需求
const handleColseAgain = async () => {
  console.log("取消操作：", againRequirementForm)
  await handleInitAgain();

  fileList.value = [];
  filePaths.value = [];
  
  dialogAgainVisible.value = false;

};

// 富文本数据更新
const updateModelValue = (newContent: any) => {
  againRequirementForm.projectMsg = newContent;
  console.log("富文本数据更新：", againRequirementForm.projectMsg);
  // return againRequirementForm.projectMsg;
};

// TODO 确定修改需求
const handleAgainRequirement = async (formEl:FormInstance | undefined) => {
  // 确定时监听富文本内容
  const againBtn = document.querySelector("#againBtn");
  againBtn?.addEventListener("update:modelValue", updateModelValue);

  if ((filePaths.value.length + againRequirementForm.filePaths.length) == 0){
    ElMessage.warning("至少上传一个附件！");
    return;
  } else {
    
    if (!formEl) {
      console.error("表单验证失败，请将内容填写完整:");
      return;
    };
    const validatePromise = formEl.validate();
    try {
      await validatePromise;
      // 表单校验通过

      // 处理需求草稿文件
      let files = [];
      files = filePaths.value.map((path: any) => {
        return handleFileName(path.resultFilePath);
      });
      againRequirementForm.filePaths.map((item: any) => {
        files.unshift(item);
      });

      await ElMessageBox.confirm("确定要修改需求吗？","确定", {
        cancelButtonText:"取消",
        confirmButtonText:"确定",
        type:"warning",
      }).then(async () => {
        //* 处理请求参数
        const reqData = {
          itemRequirementId: againRequirementForm.itemRequirementId,
          projectId: againRequirementForm.projectId,
          projectType: againRequirementForm.projectType,
          projectTitle: againRequirementForm.projectTitle,
          itemRequirementBossNameUUID: againRequirementForm.itemRequirementBossNameUUID,
          onlineTime: againRequirementForm.onlineTime,
          projectMsg: againRequirementForm.projectMsg,
          filePaths: files.map((item: any) => item.url)
        };
  
        const  { data } = await PostAgainRequirement(reqData);
        if (data.code === 200) {
          ElMessage.success(data.msg);
          dialogAgainVisible.value = false;

          againRequirementForm.itemRequirementId = null;
          againRequirementForm.projectId = null;
          againRequirementForm.projectType = null;
          againRequirementForm.projectTitle =  "";
          againRequirementForm.onlineTime = null;
          againRequirementForm.projectMsg = "";
          againRequirementForm.filePaths = [];
          
          fileList.value = [];
          filePaths.value = [];
          

          loading.value = true;
          await getAllRequirements();
          loading.value = false;

        } else {
          ElMessage.error(data.msg);
          throw console.log(data.msg);
        }

      }).catch(() => {
        dialogAgainVisible.value = false;
        againRequirementForm.itemRequirementId = null;
        againRequirementForm.projectId = null;
        againRequirementForm.projectType = null;
        againRequirementForm.projectTitle =  "";
        againRequirementForm.onlineTime = null;
        againRequirementForm.projectMsg = "";
        againRequirementForm.filePaths = [];
        
        fileList.value = [];
        filePaths.value = [];
      }); 

    } catch (error) {
      // 表单验证失败
      loading.value = false;
      console.error("表单验证失败，请将内容填写完整", error);
      return;
    }
  }
};

onMounted(async () => {
  await useCommonStore.getAllRoleUsersList("");
  await getCommon(333);
  getReviewNameOptions();
  getAllRequirements();
});
</script>

<style lang="scss" scoped>
.content-container {
  background-color: white;
  display: flex;
  flex-direction: column;
  padding: 10px;
  overflow-y: auto;

  // TODO 搜索区域
  .search-wrap {
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #dcdfe6;

    .search-wrap-item {
      margin-right: 20px;
      min-width: 200px;
      font-weight: bold;
      font-size: 24px;
      font-family: Arial, Helvetica, sans-serif;
      color: #000;
    }
  };

  // 需求列表区域
  .card-layout-box {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    padding: 0 5px 10px 5px;

    // 无数据时显示
    .card-not-requirement {
      color: #909399;
      margin: auto;
    }

   
    .card-box {
      width: 32%;
      height: 360px;
      height: 50%;
      border: 1px solid #909399;
      border-radius: 20px 20px 0 0;
      margin: 0 5px;
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;

      // 列表标题
      .card-header-box {
        width: 100%;
        height: 40px;
        padding: 0 10px;
        line-height: 40px;
        font-size: 18px;
        font-family: Helvetica, Arial, sans-serif;
        color: white;
        border-radius: 20px 20px 0 0;
      }

      // 列表盒子
      .card-list-box {
        width: 100%;
        // height: calc(100% - 40px);
        display: flex;
        justify-content: flex-start;
        overflow-y: auto;

        .card-list {
          width: 100%;
          height: 100%;
          font-size: 14px;

          .card-list-item {
            width: 100%;
            min-height: 50px;
            height: 50px;
            padding: 5px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            border-bottom: 1px solid #ccc;
            // 操作
            .operate-box {
              width: 20px;
              height: 100%;
              display: flex;
              align-items: center;

            }
            // 
            .card-list-left {
              width: calc(100% - 20px);
              display: flex;
              flex-direction: column;
              flex-wrap: nowrap;
              // 需求标题
              .card-header-title-box {
                width: 100%;
                cursor: pointer;
                .el-text {
                  width: 100%;
                }
                .el-text:hover {
                  color: #409EFF;
                }
              }
              
              // 附加信息样式
              .card-list {
                width: 100%;
                display: flex;
                justify-content: space-between;
                flex-direction: row;
                white-space: nowrap;
                padding: 0;
                font-size: 0.7rem;

                .card-list-small-item {
                  margin: 0 10px 0 0;
                }

                .item-status {
                  width: 120px;
                }

                .boss-name {
                  width: 110px;
                }

                .test-list {
                  width: 180px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                }

                .begin-time {
                  width: 110px;
                }

                .operate-box {
                  width: 20px;
                  text-align: right;
                }
              }
            }
          }
        }
      }
    }
    .card-header-title-box:hover {
      color: #409EFF;
    }
    .card-list-item:hover {
      background-color: rgb(216.8, 235.6, 255);
    }
  };

  // 审核需求
  .record-title {
    display: flex;
    flex-direction: row;
    padding: 5px 10px;
    margin-bottom: 10px;
    background-color: #f0f0f0;
    border-radius: 2px;
    p {
      margin-right: 20px;
    }
  }

  // 需求草稿
  .info-file-box {
      width: 100%;
      display: flex;
      justify-content: space-between;
      flex-direction: row;
      margin: 10px 0 0;
      .info-content-title {
          width: 100px;
          padding: 0 10px;
      }

      .info-file-ul {
          width: calc(100% - 70px);
          text-align: left;
          display: flex;
          flex-direction: row;
          .info-file-item {
              width: 100px;
              margin-right: 10px;
              color: blue;
          }
          .info-file-item:hover {
              color: #409EFF;
              cursor: pointer;
          }
      }
  }

  // TODO 分配需求弹窗
  .dialog-container {
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .dialog-form-box {
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: center;
      margin-bottom: 30px;

      .el-form-item {
        margin: 0 10px;
      }
    }

    .dialog-footer {
      text-align: right;
    }
  }

  // 修改需求弹窗
   .again-dialog {
    .create-form {
      width: 100%;
      overflow-y: auto;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      .add-icon {
        color: #dcdfe6;
        cursor: pointer;
        margin-left: 5px;
      }
      .add-icon:hover {
        color: #409eff;
      }
      .is-check-role {
        background-color: #409eff;
      }

      .file-box {
        width: 100%;
      }

      .upload-box {
        width: 100%;
        // height: 60px;
        // .el-form-item__content {
        //   align-content: flex-start;
        //   background-color: red;
        // }
      }
    }
    .create-form > *:not(.create-button) {
      order: 1;
    }
    .create-button {
      order: 2;
      margin-left: auto;
      margin-right: 20px;
      margin-top: 20px;
    }
  }
}
</style>
